package erfgame.core.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;

public class SortedList<E> extends ArrayList<E> {
	private Comparator<E> comparator;
	
	public SortedList(Comparator<E> comparator, int size ) {
		super( size );
		this.comparator = comparator;
	}
	
	public SortedList(SortedList<E> list ) {
		this( list.comparator, list.size() );
		// already sorted
		super.addAll(list);
	}

	@Override
	public boolean add(E o) {
		int index = Collections.binarySearch(this, o, comparator);
		if( index < 0 ) {
			index = -(index+1);
		}
		add(index, o);
		return true;
	}

	@Override
	public boolean addAll(Collection<? extends E> c) {
		for( E e : c ) {
			add( e );
		}
		return true;
	}

	@Override
	public boolean contains(Object elem) {
		int index = Collections.binarySearch(this, (E)elem, comparator);
		return index >= 0;
	}

	@Override
	public int indexOf(Object elem) {
		int index = Collections.binarySearch(this, (E)elem, comparator);
		return Math.max( -1, index );
	}

	@Override
	public boolean remove(Object o) {
		int index = Collections.binarySearch(this, (E)o, comparator);
		if( index >= 0 ) {
			remove( index );
			return true;
		} else {
			return false;
		}
	}
}
